"use strict";

var router = require("router"),
    TokenService = require("router").TokenService,
    mongo = require('./core/mongoservice'),
    ObjectId = require('mongodb').ObjectID,
    Q = require('q');

function UserCreationService() {
    console.log("UserCreationService constructor");
}
UserCreationService.prototype = Object.create(TokenService.prototype);
UserCreationService.prototype.constructor = UserCreationService;

UserCreationService.prototype.create = function (request, response, promise) {
    return promise.then(function (self) {
        return self.mongoInsert(request.body).then(function (user) {

            console.log("USER", JSON.stringify(user));

            var payload = { user: { id: user._id.toString()} }
            var token = self.encode(payload);

            return require("./emailservice").sendValidation(token, user).then(function () {
                return response.send({ request: request, content: user });
            });
        });
    });
};

UserCreationService.prototype.empty = function (request, response, promise) {
    return promise.then(function (self) {
        return self.getUserModel().then(function (user) {
            return response.send({ request: request, content: user });
        });
    });
};

UserCreationService.prototype.validate = function (request, response, promise) {
    return promise.then(function (self) {
        self.identify(request, response);
        var userId = request.payload.user.id;

        return self.mongoValidate(userId).then(function (user) {
            return response.redirect("/#login");
            //return response.send({ request: request, content: user });
        });
    });
};

/*-------------------------------------------------------*/
/*mongo daf*/
UserCreationService.prototype.mongoInsert = function (user) {
    if (!user) throw new Error("User is not defined.");
    if (user._id) throw new Error("User already has id: " + user._id);
    var self = this;

    return require("./referenceservice").mongoIsLoginAuthorized(user.login).then(function () {
        return self.mongoGetByLogin(user.login).then(function (res) {
            return require('./userservice').validate(user).then(function (user) {
                return mongo.insert('users.creation', user).then(function (users) {
                    return users[0];
                }).then(function (user) {
                    return require("./referenceservice").mongoInsert(user.login, user._id, "user.creation").then(function () {
                        return user;
                    });
                });
            });
        });
    });
};

UserCreationService.prototype.mongoRemove = function (userId) {
    if (!userId) throw new Error("userId is not defined.");
    var self = this;

    return self.mongoGetById(userId).then(function (user) {
        return mongo.remove('users.creation', { _id: new ObjectId(userId) });
    });
};

UserCreationService.prototype.mongoGetById = function (userId) {
    if (!userId) throw new Error("userId is not defined.");

    return mongo.findOne('users.creation', { _id: new ObjectId(userId) });
};

UserCreationService.prototype.mongoGetByLogin = function (login) {
    if (!login) throw new Error("login is not defined.");

    return mongo.findOne('users.creation', { login: login });
};

UserCreationService.prototype.mongoValidate = function (userId) {
    if (!userId) throw new Error("userId is not defined.");
    var self = this;

    return self.mongoGetById(userId).then(function (user) {
        return self.mongoRemove(user._id).then(function () {
            return require('./referenceservice').mongoRemove(user._id, "user.creation").then(function () {
                delete user._id;
                return require('./userservice').mongoInsert(user);
            });
        });
    });
    return mongo.findOne('users.creation', { _id: new ObjectId(userId) });
};

UserCreationService.prototype.getUserModel = function () {
    return Q.fcall(function () {
        return {
            login: "",
            password: "",
            contact: {
                email: ""
            },
            location: {
                address: "",
                city: "",
                postal_code: "",
                loc: {
                    type: "Point",
                    coordinates: []
                }
            },
            picto: {
                src: "/api/image/user/picto/default"
            },
            dates: {
                creation: null
            },
            shops: {
                subscriptions: [],        /*liste de boutique abonnées*/
                near: [],                 /*liste de boutique proche*/
                employers: []              /*liste de boutique dans laquelle l'utilisateur travaille*/
            },
            users: {
                subscriptions: [],        /*amis*/
                near: []                  /*liste d'utilisateur proche*/
            },
            config: {
                distanceM: 2000
            }
        };
    });
};


exports = module.exports = new UserCreationService();